package com.apestech.framework.web;


import com.apestech.framework.json.JSON;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.util.LocalVariable;
import com.apestech.framework.web.lib.Http;
import org.junit.Test;

import java.io.*;


/**
 * @author hup
 * @create 2018-09-18-11:47
 */
public class HttpUtil {

    public static JSONObject postEsb(String method) throws Exception {
        return execEsb(getESBUrl(), method, null, true);
    }

    public static JSONObject getEsb(String method) throws Exception {
        return execEsb(getESBUrl(), method, null, false);
    }

    public static JSONObject postEsb(String method, JSONObject input) throws Exception {
        return execEsb(getESBUrl(), method, JSON.toJSONString(input), true);
    }

    public static JSONObject getEsb(String method, JSONObject input) throws Exception {
        return execEsb(getESBUrl(), method, JSON.toJSONString(input), false);
    }

    public static JSONObject postEsb(String method, String input) throws Exception {
        return execEsb(getESBUrl(), method, input, true);
    }

    public static JSONObject getEsb(String method, String input) throws Exception {
        return execEsb(getESBUrl(), method, input, false);
    }

    private static String getESBUrl(){
        String url=LocalVariable.getSysUrl("ESB");
        if(url==null){
            url="http://localhost:6060/router";
            LocalVariable.setSysUrl("ESB", url);
        }
        return url;
    }

    private static JSONObject execEsb(String url, String method, String input, boolean post) throws Exception {
        JSONObject map=new JSONObject();
        map.put("appKey", "00001");
        map.put("version", "1.0");
        map.put("method", method);
        if(input!=null){
            map.put("body", input);
        } else {
            map.put("body", "{}");
        }
        Http http=new Http(url, map);
        try {
            String json;
            if(post){
                json=http.post();
            } else {
                json=http.get();
            }
            return JSON.toJSON(json);
        } catch (IOException e) {
            throw new Exception(e);
        }
    }

    @Test
    public void test() throws Exception {
        //"{\"condition\":[],\"size\":50,\"page\":1,\"table\":\"crm_customer_car\",\"type\":\"page\",\"sumfield\":\"\",\"formatfield\":{}, \"sqltype\":\"select\"}"
        System.out.println(postEsb("pub.queryForTable","{\"condition\":[],\"size\":50,\"page\":1,\"table\":\"crm_customer_car\",\"type\":\"page\",\"sumfield\":\"\",\"formatfield\":{}, \"sqltype\":\"select\"}"));
    }

}
